<template>
    <div class="jeecg-basic-table-form-container">
      <a-form @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="8">
            <a-form-item label="账单周期">
              <a-date-picker v-model:value="queryParam.date" picker="month" />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="保险公司">
              <j-dict-select-tag v-model:value="queryParam.company" dictCode="BXGS" placeholder="请选择保险公司"  />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                 <a-button class="export-btn" type="primary" preIcon="ant-design:export-outlined" style="margin-left: 8px" @click="exportXls"> 导出</a-button>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-table :columns="columns" :data-source="data" bordered :pagination="false" :scroll="{ x: 1200, y: 700 }">
      <template #bodyCell="{ column, text }">
        <template v-if="column.dataIndex === 'name'">
          <a href="javascript:;">{{ text }}</a>
        </template>
      </template>
    </a-table>
</template>

<script lang="ts" name="salesman-report" setup>
  import { BasicTable, TableAction } from '/@/components/Table';
  import { ref, reactive, onMounted } from 'vue';
  import { dateFormat } from '/@/utils/common/compUtils';
  import { useMethods } from '/@/hooks/system/useMethods';
  import { columns } from './salesmanReport.data';
  import { list, getExportUrl } from './salesmanReport.api';
  import dayjs from 'dayjs';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';

  const { handleExportXls } = useMethods();
  const queryParam = ref<any>({
    date: dayjs().add(-1,'month'),
  });
  const data = ref<any[]>([]);
  //注册table数据
  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 7 },
  });
  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 16 },
  });

  onMounted(() => {
    // const payBegin = dayjs().startOf('month');
    // queryParam.value.date = payBegin;
    handleRequest();
  });

  function handleRequest() {
    list(queryParam.value).then((res) => {
      const list = mergeRows(res);
      data.value = list;
    });
  }
  function exportXls() {
    const date = dateFormat(queryParam.value.date, 'yyyy-MM-dd');
    return handleExportXls('业务员报表', getExportUrl, { date, company: queryParam.value.company });
  }
  function mergeRows(rows) {
    const groupMap = {};
    // 遍历每一行数据
    rows.forEach((row) => {
      // 获取当前行的id
      const name = row.salesman;
      // 如果id已经存在于groupMap中，则将当前行添加到对应的组中
      if (groupMap[name]) {
        groupMap[name].push(row);
      } else {
        // 否则，创建一个新的组，并将当前行添加到该组中
        groupMap[name] = [row];
      }
    });
    // 遍历groupMap，取出数组计算数组中每一项的合计数量
    let list: any[] = [];
    for (const name in groupMap) {
      const group = groupMap[name];
      let cost = 0;
      let exTaxPremium = 0;
      let insuranceFee = 0;
      let salesmanFee = 0;
      let systemFee = 0;
      let proxyFree = 0;
      let income = 0;
      let incomeRate = 0;
      group.forEach((item, index) => {
        if (index === 0) {
          item.rowSpan = group.length;
        } else {
          item.rowSpan = 0;
        }
        cost += item.cost;
        exTaxPremium += item.exTaxPremium;
        insuranceFee += item.insuranceFee;
        salesmanFee += item.salesmanFee;
        systemFee += item.systemFee;
        proxyFree += item.proxyFree;
        income += item.income;
      });
      if (exTaxPremium != 0) {
        incomeRate = (income / exTaxPremium) * 100;
      }

      const total = {
        area: '合计',
        cost,
        exTaxPremium,
        insuranceFee,
        salesmanFee,
        systemFee,
        proxyFree,
        income,
        incomeRate,
        rowSpan: 1,
      };
      // 将合计加入小数组中
      group.push(total);
      list = [...list, ...group];
    }
    return list;
  }
  /**
   * 查询
   */
  function searchQuery() {
    handleRequest();
  }
</script>

<style lang="less" scoped>
.jeecg-basic-table-form-container {
  .table-page-search-submitButtons {
    display: block;
    margin-bottom: 24px;
    white-space: nowrap;
  }
  .query-group-cust {
    width: calc(50% - 15px);
    min-width: 100px !important;
  }
  .query-group-split-cust {
    width: 30px;
    display: inline-block;
    text-align: center;
  }
}
</style>
